# coding=UTF-8

# 转换格式
def parse_x(data, key, val):
    x = []
    for k in data.keys():
        x.append({'key': data[k][key], 'val': data[k][val]})
    return x


# x 为数据
def MACD(x):
    # < 1 > 计算12日和26日移动平均线EMA1和EMA2
    # 当日EMA(12) = 前一日EMA(12)×11 / 13＋当日收盘价×2 / 13
    # 当日EMA(26) = 前一日EMA(26)×25 / 27＋当日收盘价×2 / 27
    # < 2 > 计算离差值(DIFF)
    # DIFF = 当日EMA(12)－当日EMA(26)
    # <3>计算9日离差平均值DEA
    # 当日DEA=前一日DEA×8/10＋当日DIFF×2/10
    # < 4 > 计算MACD
    # MACD = 2×(DIFF－DEA)
    if len(x) == 0:
        return []
    macd_list = [{'key': x[0]['key'], 'val': 0}]
    tmp_info = {'ema12': x[0]['val'], 'ema26': x[0]['val'], 'dea': 0}
    for i in range(1, len(x)):
        key = x[i]['key']
        val = x[i]['val']
        ema12 = (tmp_info['ema12'] * 11 + val * 2) / 13
        ema26 = (tmp_info['ema26'] * 25 + val * 2) / 27
        diff = ema12 - ema26
        dea = (tmp_info['dea'] * 8 + diff * 2) / 10
        macd = 2 * (diff - dea)
        tmp_info['ema12'] = ema12
        tmp_info['ema26'] = ema26
        tmp_info['dea'] = dea
        macd_list.append({'key': key, 'val': macd})
    return macd_list


if __name__ == '__main__':
    macd_list1 = MACD('600031', '2021-03-01', 10, 30)
    for num in range(len(macd_list1)):
        print(macd_list1[num])
